<template>
  <view class="ve-checkbox" @tap="toggle">
    <view class="ve-checkbox__icon-wrap">
      <text class="checkbox__icon-wrap__icon iconfont" :class="iconName" :style="iconStyle"></text>
    </view>
    <view class="ve-checkbox__label">
      <slot />
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref, computed, watch, inject } from 'vue'

  const checkboxProvide: any = inject('checkboxProvide')
  const emit = defineEmits(['update:modelValue', 'change'])
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    name: {
      type: String,
      default: '',
    },
  })
  const checked = ref(false)
  const iconName = computed(() => {
    return checked.value ? 've-icon-checked-nocolor' : 've-icon-ic_checkbox_line'
  })
  const iconStyle = computed(() => {
    const style: any = {}
    if (checked.value) {
      style.color = 'rgba(22, 93, 255, 1)'
    } else {
      style.color = 'rgba(229, 230, 235, 1)'
    }
    return style
  })

  const toggle = () => {
    setValue()
  }

  const emitEvent = () => {
    emit('change', {
      value: checked.value,
      name: props.name,
    })
    if (!checkboxProvide) return
    if (checked.value) {
      checkboxProvide.children.value.push({
        checked: checked.value,
        name: props.name,
      })
    } else {
      checkboxProvide.children.value.forEach((item: any, index: number) => {
        if (item.name === props.name) {
          checkboxProvide.children.value.splice(index, 1)
        }
      })
    }
    checkboxProvide.emitEvent()
  }

  const setValue = () => {
    checked.value = !checked.value
    emit('update:modelValue', checked.value)
    emitEvent()
  }

  watch(
    () => props.modelValue,
    (value) => {
      checked.value = value
    },
    { immediate: true },
  )
</script>

<style lang="less" scoped>
  .ve-checkbox {
    cursor: pointer;
    display: flex;
    align-items: center;
    margin-left: 32rpx;
    .ve-checkbox__label {
      font-size: 28rpx;
      font-weight: 400;
      color: #1d2129;
      margin-left: 12rpx;
    }
  }
  .ve-checkbox__icon-wrap {
    .checkbox__icon-wrap__icon {
      display: block;
      font-size: 38rpx;
      height: 38rpx;
    }
  }
</style>
